﻿using AmiDraw.Lib.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Panuon.UI.Silver;
using Panuon.UI.Core;
using AmiDraw.Lib.Factory;
using PropertyChanged;
using System.Windows.Media.Imaging;
using System.Windows.Interop;
using System.Windows;

namespace AmiDraw.Editor.ViewModel
{
    [AddINotifyPropertyChangedInterface]
    public class DrawSimulatorViewModel
    {
        public AcPackInfo PackInfo { get; set; }

        public ObservableCollection<DrawResult> Results { get; set; } = new();

        public int DrawTime { get; set; } = 1;

        public bool IsGuarantee { get; set; } = false;

        public bool UseBigImage { get; set; } = false;


        public BitmapSource ResultBitmapSource { get; set; }


        public RelayCommand DrawCommand { get; set; }
        public RelayCommand Draw100Command { get; set; }
        public RelayCommand ClearCommand { get; set; }

        public DrawSimulatorViewModel()
        {
            DrawCommand = new RelayCommand(Draw);
            ClearCommand = new RelayCommand(Clear);
            Draw100Command = new RelayCommand(Draw100);
        }

        public void Draw(object obj)
        {
            for (int i = 0; i < DrawTime; i++)
            {
                Results.Add(DrawFactory.Draw(PackInfo.Name, IsGuarantee, Lib.ResultQueryMode.Editor));
            }

            var bitmap = new DrawerFactory(PackEditViewModel.instance.DirectoryInfo.Name, Results.ToList(),
                Lib.ResultQueryMode.Editor);
            ResultBitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GenerateImage().GetHbitmap(), IntPtr.Zero,
                Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
        }

        public void Clear(object obj)
        {
            Results.Clear();
        }

        public void Draw100(object obj)
        {
            List<DrawResult> list = new();
            for (int i = 0; i < 100; i++)
            {
                list.Add(DrawFactory.Draw(PackInfo.Name, IsGuarantee, Lib.ResultQueryMode.Editor));
            }

            StringBuilder sb = new();
            sb.AppendLine($"进行了100次连抽!");
            var groupBy = list.GroupBy(x => x.LevelInfo.Name).Select(x => x.First().LevelInfo);
            foreach (var levelgroup in groupBy)
            {
                sb.AppendLine($"等级{levelgroup.Name},总计出现{list.Count(x => x.LevelInfo.Name == levelgroup.Name)}");
                sb.AppendLine($"{levelgroup.Ratio}/{list.First().SumRatio}");
            }

            sb.AppendLine($"进行了100次连抽!");

            MessageBox.Show(sb.ToString());
        }
    }
}